package com.example.simplesvc.notification;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.simplesvc.concurrent.lock.DBLockFactory;
import com.example.simplesvc.entity.Reconciliation;
import com.example.simplesvc.event.ReconciliationEvent;
import com.example.simplesvc.mappers.ReconciliationMapper;
import org.apache.http.client.utils.DateUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.function.Function;


@Component
public class ReconciliationEventListener implements ApplicationListener<ReconciliationEvent> {


    @Autowired
    ReconciliationMapper mapper;

    @Autowired
    DBLockFactory factory;



    @Override
    public void onApplicationEvent(ReconciliationEvent event) {
        Reconciliation reconciliation = new Reconciliation();
        reconciliation.setName(DateUtils.formatDate(new Date(),"yyyyMMdd"));
        reconciliation.setStartTime(event.getStartTime());

        factory.getLock("reconciliation").executeWithLock(new Callable() {
            @Override
            public Object call() {
               List<Reconciliation> list = mapper.selectList(Wrappers.lambdaQuery(Reconciliation.class).eq(Reconciliation::getName, reconciliation.getName()));

                if(!event.isFinished() && list.isEmpty()) {
                        mapper.insert(reconciliation);
                }

                if(event.isFinished()) {
                    reconciliation.setEndTime(event.getEndTime());
                    int i =  mapper.update(reconciliation, Wrappers.lambdaUpdate(Reconciliation.class).eq(Reconciliation::getName, reconciliation.getName()));
                }
                return null;
            }
        });






        //
        //记录开始时间和结束时间
    }


}
